﻿var jcrop_api = null;
var imagePanel = $('#imagePanel');

imagePanel.Jcrop({
    setSelect: [0, 0, 800, 400]
}, function () {
    jcrop_api = this;
});


function setWidth() {
    var width = parseInt($('#width').val());
    if (isNaN(width)) return;
    var zone = jcrop_api.tellSelect();
    jcrop_api.setSelect([zone.x, zone.y, zone.x + width, zone.y2]);
}
function setHeight() {
    var height = parseInt($('#height').val());
    if (isNaN(height)) return;
    var zone = jcrop_api.tellSelect();
    jcrop_api.setSelect([zone.x, zone.y, zone.x2, zone.y + height]);
}
function zoom_down() {
    jcrop_api.destroy();
    var width = imagePanel.width();
    var newWidth = width - 100;
    if (newWidth <= 100) newWidth = 100;

    var position = jcrop_api.tellSelect();
    imagePanel.css('height', 'auto');
    imagePanel.animate({ 'width': newWidth }, 100, function () {
        imagePanel.Jcrop({
            handleSize: 9,
            allowSelect: false,
            setSelect: [position.x, position.y, position.x2, position.y2]
        }, function () {
            jcrop_api = this;
        });

    });
}
function zoom_up() {
    jcrop_api.destroy();
    var width = imagePanel.width();
    var newWidth = width + 100;
    if (newWidth >= 800) newWidth = 800;

    imagePanel.css('height', 'auto');

    var position = jcrop_api.tellSelect();
    console.log([position.x, position.y, position.x2, position.y2]);

    imagePanel.animate({ 'width': newWidth }, 100, function () {
        imagePanel.Jcrop({
            handleSize: 9,
            allowSelect: false,
            setSelect: [position.x, position.y, position.x2, position.y2]
        }, function () {
            jcrop_api = this;
        });
    });
}

function preview() {
    var url = getPreviewURL();
    $('#previewPanel').html('<img src="' + url + '">');
}

function save() {
    var url = getPreviewURL();
    url = url + "&save=true";
    $.post(url).success(function (savePth) {
        if (parent && parent.editPictureCallBack) parent.editPictureCallBack(savePth);
        if (parent && parent.on_picture_edit_callback) parent.on_picture_edit_callback(savePth);
    }).error(function () {
        alert('保存失败，请重试');
    });
}

function getPreviewURL() {
    var displayBounds = jcrop_api.getBounds();
    var position = jcrop_api.tellSelect();

    var option = {
        path: encodeURIComponent($('#originPicture').val()),
        displayWidth: displayBounds[0],
        displayHeight: displayBounds[1],
        leftTopX: position.x,
        leftTopY: position.y,
        width: position.w,
        height: position.h
    };

    var r = [];
    for (var key in option) {
        r.push(key + '=' + option[key]);
    }
    return location.origin + '/image/preview?' + r.join('&');

}